import { reqCarList, reqDeleteCarBySkuId, reqUpdateCheckedByid } from '@/api'

const state = {
  carList: []
}
const mutations = {
  GETCARLIST (state, carList) {
    state.carList = carList
  }
}
const actions = {
  // 获取购物车列表数据
  async getCarList ({ commit }) {
    let result = await reqCarList()
    if (result.code == 200) {
      commit('GETCARLIST', result.data)
    }
  },

  // 删除购物车产品
  async deleteCarBySkuId ({ commit }, skuId) {
    let result = await reqDeleteCarBySkuId(skuId)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  // 修改购物车产品勾选状态
  async updateCheckedById ({ commit }, { skuId, isChecked }) {
    let result = await reqUpdateCheckedByid(skuId, isChecked)
    if (result.code == 200) {
      return 'ok'
    } else {
      return Promise.reject(new Error('faile'))
    }
  },
  deleteAllCheckedCart ({ getters, dispatch }) {
    // context：小仓库，commit提交mutations修改state状态，getters 计算属性 dispatch 派发action state 当前仓库数据
    // 获取购物车中全部的产品，数组
    // console.log(context)
    // console.log(getters)
    let PromiseAll = []
    getters.carList.cartInfoList.forEach(item => {
      let promise = item.isChecked == 1 ? dispatch('deleteCarBySkuId', item.skuId) : ''
      // 将每一次返回的Promise添加到数组当中
      PromiseAll.push(promise)
    })
    // 只要全部的P1,P2..都成功，返回结果即为成功
    // 如果有一个失败，返回即为失败结果
    return Promise.all(PromiseAll)
  },
  // 修改所有产品勾选状态
  updateAllCartChecked({dispatch,state},isChecked){
    let PromiseAll = []
     state.carList[0].cartInfoList.forEach(item=>{
       let promise=dispatch('updateCheckedById',{skuId:item.skuId,isChecked})
       PromiseAll.push(promise)
     })
    return Promise.all(PromiseAll)
  }
}
const getters = {
  carList (state) {
    return state.carList[0] || {}
  }
}
export default {
  state, mutations, actions, getters
}
